package com.nextbusmn.server.services;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.nextbusmn.server.JDOWrappers.BusRouteJDOWrapper;
import com.nextbusmn.server.JDOWrappers.BusStopJDOWrapper;
import com.nextbusmn.server.JDOWrappers.BusTripJDOWrapper;
import com.nextbusmn.server.JDOWrappers.StopTimeJDOWrapper;
import com.nextbusmn.server.JSONBuilders.RouteJSONBuilder;
import com.nextbusmn.server.JSONBuilders.SingleStopJSONBuilder;
import com.nextbusmn.server.dataobjects.BusRouteData;
import com.nextbusmn.server.dataobjects.BusStopData;
import com.nextbusmn.server.dataobjects.BusTripData;
import com.nextbusmn.server.dataobjects.StopTimeData;

public class StopInfoService implements AndroidService {

	private final int stopID;
	private HttpServletResponse response;
	
	public StopInfoService(String request, HttpServletResponse response) {
		stopID = Integer.parseInt(request); //TODO catch number format ex
		this.response = response;
	}
	
	@Override
	public void processRequest() {
		try {
			JSONObject jsonResponse = getStopInfo();
			
			response.setContentType("application/json");
	        response.setHeader("Cache-Control", "no-cache");
	        response.getWriter().write(jsonResponse.toString());
		} catch (IOException e) {
			AndroidService errorService = 
					new ErrorService("IOError on Stop Info Service response", response);
			errorService.processRequest();
			// TODO create appropriate error
			//throw new AndroidRequestError(shapeID, "IOError on Map Service response");
		}
	}
	
	private JSONObject getStopInfo() {
		
		BusStopData stopData = BusStopJDOWrapper.getByStopID(stopID);
		
		return SingleStopJSONBuilder.getSingleStopJSON(stopData);
	}

}
